package com.levy.contronller.javaWeb.findImageTest;

import cn.hutool.core.io.FileUtil;
import com.baidu.aip.ocr.AipOcr;
import com.levy.utils.FileTool.TextFileUtils;
import com.levy.utils.FileUtils;
import com.levy.utils.StringUtils1;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

/**
 * Created by levy on 2018/11/5.
 */
public class BaiduFormOcrUtils {

    //设置APPID/AK/SK
    private static final String APP_ID = "14318143";
    private static final String API_KEY = "b3cUNTdGpclWadQF9Yr8Gavy";
    private static final String SECRET_KEY = "M1AktIZRfAlAttFSrvzzW833X3KeFuFI";
    private static AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);


    public static String getFormOcrRequestId(String imgPath) throws IOException {
        // 参数为本地图片路径

        JSONObject res = client.tableRecognitionAsync(imgPath, null);
        System.out.println(res.toString(2));
        JSONArray result = res.getJSONArray("result");
        String requestId = result.getJSONObject(0).getString("request_id");
        return requestId;
    }


    public static String getRequestResult(String type, String requestId) throws InterruptedException {
        JSONObject json = null;
        String result = "";
        boolean isProccesing = true;
        while (isProccesing) {
            JSONObject resJson = null;
            Thread.sleep(5000);
            if ("json".equals(type)) {
                json = client.getTableRecognitionJsonResult(requestId);
            } else {
                json = client.getTableRecognitionExcelResult(requestId);
            }
            System.out.println("----" + json);
            if (json != null) {
                try {
                    if (!json.toString().contains("error_code")) {
                        resJson = json.getJSONObject("result");
                        if (result != null) {
                            String retMsg = resJson.getString("ret_msg");
                            if ("已完成".equals(retMsg)) {
                                result = resJson.getString("result_data");
                                isProccesing = false;
                            }
                        }
                    }else{
                        isProccesing = false;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println(resJson.toString());
                }
            }
        }
        return result;
    }


    public static String getConvertResult(String imgPath, String type) throws IOException, InterruptedException {
        String formOcrRequestId = getFormOcrRequestId(imgPath);
        String requestResult = getRequestResult(type, formOcrRequestId);
        return requestResult;
    }

    @Test
    public void test() {

        String imgPath = "G://pdf/small//pdfbox_image_71.png";
        String savePath = "G://pdf/html//secondTable//pdfbox_image_71_baidu.xlsx";
        try {
            String type = "excel";
            String convertResult = getConvertResult(imgPath, type);
            System.out.println(convertResult);
            //excle
            if (!"json".equals(type) && StringUtils1.isNotBlank(convertResult)) {
                FileUtils.downLoadFromUrl(convertResult, savePath);
            } else {
                TextFileUtils.write("G:\\pdf\\8_bd.json", convertResult, "utf-8");
            }
            System.out.println("over");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public static void main(String[] args) throws Exception {
        long l = System.currentTimeMillis();
        String imgFileDir = "G://pdf/small//";
        String saveFileDir = "G://pdf/html//BAIDU//";
        List<String> fileNames = FileUtil.listFileNames(imgFileDir);
        for (String s : fileNames) {
            String pdfbox_image_ = s.replaceAll("pdfbox_image_", "").replaceAll(".png", "");
            int i = Integer.parseInt(pdfbox_image_);
            String imgFile = imgFileDir + s;
            String fileNameWithOutSuff = s.substring(0, s.indexOf(".png")) + ".xlsx";
            String saveFile = "";
            if (i > 52 && i < 59) {
                saveFile = saveFileDir + "//firstTable//" + fileNameWithOutSuff;
            } else if (i > 58) {
                saveFile = saveFileDir + "//secondTable//" + fileNameWithOutSuff;
            } else {
                continue;
            }

            String type = "excel";
            String convertResult = getConvertResult(imgFile, type);
            System.out.println(convertResult);
            //excle
            if (!"json".equals(type) && StringUtils1.isNotBlank(convertResult)) {
                FileUtils.downLoadFromUrl(convertResult, saveFile);
            } else {
                TextFileUtils.write(saveFile, convertResult, "utf-8");
            }
            System.out.println("over");
        }
        System.out.println((System.currentTimeMillis() - l) / 1000);
    }

}
